# -*- coding: utf-8 -*-
# @Date   : 2021/03/31
# @File   : CF11_ARRatioAnnualGradientInThree.py
# @Author : zhanghengfeng

'''eof
name:近3年收汇率年均变化率
code:CF11_ARRatioAnnualGradientInThree
tableName:
columnName:
groups:出口信息模块
dependencies:CF_CQ_DSJ
type:常用指标
dataSourceType:
eof'''

from __future__ import division 
import numpy as np
import pandas as pd
import datetime

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def ratelist_method():
    '''
    Explanation
    --------------
    获取近期指定月份数长度升序排列的出口货物金额列表
        
    Return
    ------
    amount_list: list or str
        收汇率列表
    '''

    #获取exchangeRate表失败时，返回缺失值
    try:
        exchangeRate = data['body']['baseInfo'][0]['exchangeRate']
        if exchangeRate in null_type_list or exchangeRate == []:
            return u'缺失值'
        elif isinstance(exchangeRate,list) and len(exchangeRate)>0:
            #获取当前时间年份前推两年
            yearlist = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset\
                                (years=i)).strftime('%Y%m%d')[:4] for i in range(1, 4)]
            yearlist_str = []
            for i in yearlist:
                yearlist_str.append(str(i))
        
            #根据上述列表生成对应月份为0元的记录的字典
            rate_dict = {}
            for i in range(len(yearlist_str)):
                rate_dict[yearlist_str[i]] = None
            
            #遍历所有的申报记录，对相应月份进行字段值更新 
            errorConts = 0
            for i in exchangeRate:
                try:
                    #收汇率
                    collectRate = i.get('collectRate')
                    #收汇年份
                    year = i.get('year')
                    if isfloat(collectRate) and isfloat(year) and isinstance(int(year),int) and len(year) == 4:
                        if year in yearlist and rate_dict[year] == None and float(collectRate) > 0:
                            rate_dict.update({year:float(collectRate)})
                        else:
                            pass
                    else:
                        errorConts += 1
                except:
                    errorConts += 1
            if errorConts == len(exchangeRate):
                return u'缺失值'
            else:                      
                #按年份对字典进行降序排列，现在目测数据条目是时间顺序排列的，所以还是先排个序稳当点
                rate_dict_f = {}
                for i in sorted (rate_dict):
                    rate_dict_f[i] = rate_dict[i]
                #返回列表形式的字典字段值,使用last_month_dict_f.values()会打乱顺序
                rate_list = list(pd.DataFrame([rate_dict_f]).iloc[0,:])
                return rate_list
        else:
            return u'缺失值'
    except:
        return u'缺失值' 

def CF11_ARRatioAnnualGradientInThree():
    try:
        list_result = ratelist_method()
        if list_result == u'缺失值' or list_result[1] == None:
            return u'缺失值'
    except:
        return u'缺失值'
    list_result = [x for x in list_result if x is not None]
    list_result=list(reversed(list_result))
    cal_ratio = []
    for i in range(len(list_result)-1):
        if list_result[i+1] == 0:
            cal_ratio.append(0)
        else:
            cal_ratio.append((list_result[i] - list_result[i+1])/list_result[i+1])
    return round(np.mean(cal_ratio),4)

result = CF11_ARRatioAnnualGradientInThree()